<template>
  <el-dialog title="角色分配" :visible.sync="dialog" @close="closeDialog">
    <el-form class="form-box" ref="userInfoForm" label-width="100px">
      <el-form-item label="当前用户">{{userName}}</el-form-item>
      <el-form-item label="角色" disabled>{{role_name}}</el-form-item>
      <el-form-item label="角色选项">
        <el-select v-model="selectValue" placeholder="请选择">
          <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialog = false">取 消</el-button>
      <el-button type="primary" @click="edit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
export default {
  data () {
    return {
      dialog: false,
      roles: [],
      selectValue: '',
      userId: 0,
      role_name: '',
      userName: ''
    }
  },
  methods: {
    async getRoles () {
      const { data: res } = await this.axios.get('roles')

      if (res.meta.status !== 200) { return this.$message.error('获取角色列表失败') }
      this.roles = res.data
      console.log(this.roles)
    },
    // 弹窗打开
    openDialog (data) {
      this.getRoles()

      this.userId = data[1].id
      this.userName = data[1].username
      this.role_name = data[1].role_name
      this.dialog = data[0]
    }, // 弹窗关闭
    closeDialog () {
      // this.$refs.userInfoForm.resetFields();
      this.selectValue = ''
      this.roles = []
    },
    // 编辑用户
    async edit () {
      // this.$refs.userInfoForm.validate(async status => {
      //   console.log(status);
      //   if (!status) {
      //     return this.$message.error("请填写正确信息");
      //   }
      const { data: res } = await this.axios.put(
        'users/' + this.userId + '/role',
        { rid: this.selectValue }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.$message.success(res.meta.msg)
        // 关闭弹窗
        this.dialog = false
        // 重新获取数据
        this.$parent.getUserList()
      }
      // });
    }
  }
}
</script>
